package com.ruoyi.framework.provider;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 重写动态数据库提供者
 */
@Slf4j
@Component
public class CustomDataSourceProvider implements DynamicDataSourceProvider {
    @Autowired
    private DynamicDataSourceProperties dynamicDataSourceProperties;
    @Autowired
    private DefaultDataSourceCreator dataSourceCreator;
    @Autowired
    private DynamicDatabasePasswordProvider passwordProvider;


    @Override
    public Map<String, DataSource> loadDataSources() {
        log.info("开始加载数据源");
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        Map<String, DataSourceProperty> dataSourcePropertyMap = dynamicDataSourceProperties.getDatasource();
        dataSourcePropertyMap.forEach((key, dataSourceProperty) -> {
            //按条件替换获取密码
            if (StrUtil.isBlank(dataSourceProperty.getPassword()) || "<remote-db-password>".equals(dataSourceProperty.getPassword())) {
                String decryptedPassword = passwordProvider.getPassword();
                dataSourceProperty.setPassword(decryptedPassword);
            }
            DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
            dataSourceMap.put(key, dataSource);
        });
        return dataSourceMap;
    }

}
